<?php

namespace App\Supports\Qrcode;

use EasyWeChat;
use App\Models\User;
use App\Models\Product;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class MiniQrcode
{
	protected $mini;
	
	protected $inviter;
	protected $product = null;
	
	public function __construct(User $user, Product $product = null)
	{
		$route = config('wxpay.default');
		$items = config("wxpay.{$route}");
		
		$config = [
			'app_id'  => $items['miniapp_id'],
			'secret'  => $items['miniapp_sc'],
		];
		
		$this->mini = Factory::miniProgram($config);
		
		$this->inviter = $user;
		$this->product = $product;
	}
	
	protected function getQrcodeName()
	{
		if ($this->product) {
			$name = "qrcode-user-{$this->inviter->id}-product-{$this->product->id}.png";
		} else {
			$name = "qrcode-user-{$this->inviter->id}.png";
		}
		return $name;
	}
	
	protected function getLocalQrcodeDir()
	{
		$localPath = public_path('temp/mini-product-invite-qrcodes');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return $localPath;
	}
	
	protected function getLocalQrcodeSavePath()
	{
		return $this->getLocalQrcodeDir() . '/' . $this->getQrcodeName();
	}
	
	protected function getRemoteQrcodeDir()
	{
		return 'images/mini-product-invite-qrcodes';
	}
	
	protected function getRemoteQrcodeSavePath()
	{
		return $this->getRemoteQrcodeDir() . '/' . $this->getQrcodeName();
	}
	
	public function make(string $scene, array $params)
	{
		if (Storage::exists($this->getRemoteQrcodeSavePath())) {
			return Storage::url($this->getRemoteQrcodeSavePath());
		}
		
		$mini = $this->mini;
		$response = $mini->app_code->getUnlimit($scene, $params);
		
		if (! $response instanceof EasyWeChat\Kernel\Http\StreamResponse) {
			abort(500, '小程序二维码生成失败，请重试');
		}
		
		// save to local
		$response->saveAs($this->getLocalQrcodeDir(), $this->getQrcodeName());
		
		// move to oss
		Storage::putFileAs($this->getRemoteQrcodeDir(), $this->getLocalQrcodeSavePath(), $this->getQrcodeName());
		
		// remove local poster
		File::delete($this->getLocalQrcodeSavePath());
		
		return Storage::url($this->getRemoteQrcodeSavePath());
	}
}
